package com.haidada.tk.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.Collections;
import java.util.List;

/**
 * 分页
 *
 * @param <T>
 * @author admin
 */
@ApiModel("分页数据")
public class PageUtils<T> {
    private static final PageUtils<?> EMPTY = new PageUtils<>();

    @ApiModelProperty("每页显示记录数")
    private int pageSize = 10;

    @ApiModelProperty("页码，从1开始")
    private int number = 1;

    @ApiModelProperty("总的记录数")
    private long totalElements;

    @ApiModelProperty("数据")
    private List<T> content = Collections.emptyList();

    public PageUtils() {

    }

    public static <T> PageUtils<T> of(org.springframework.data.domain.Page<T> page) {
        return new PageUtils<>(page.getSize(), page.getNumber() + 1, page.getTotalElements(), page.getContent());
    }

    public PageUtils(int pageSize, int number, long totalElements) {
        this.totalElements = totalElements;
        this.pageSize = pageSize;
        this.number = number;
    }

    public PageUtils(int pageSize, int number) {
        this.pageSize = pageSize;
        this.number = number;
    }

    public PageUtils(int pageSize, int number, long totalElements, List<T> content) {
        this.pageSize = pageSize;
        this.number = number;
        this.totalElements = totalElements;
        this.content = content;
    }

    public static <T> PageUtils<T> empty() {
        @SuppressWarnings("unchecked")
        PageUtils<T> t = (PageUtils<T>) EMPTY;
        return t;
    }

    @JsonIgnore
    public int getStart() {
        return (this.number - 1) * getPageSize();
    }

    /**
     * 总页数
     *
     * @return 总页数
     */
    @ApiModelProperty("总的页数")
    public long getTotalPages() {
        if (totalElements % pageSize == 0) {
            return totalElements / pageSize;
        } else {
            return totalElements / pageSize + 1;
        }
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public List<T> getContent() {
        return content;
    }

    public void setContent(List<T> content) {
        this.content = content;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(long totalElements) {
        this.totalElements = totalElements;
    }

    @Override
    public String toString() {
        return "Page [pageSize=" + pageSize + ", number=" + number + ", totalElements=" + totalElements + ", content="
                + content + "]";
    }
}
